import axios from 'axios'
// import router from '../routers'
import mitt from 'mitt';
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useWebSocket } from '@/stores/websocket'
import { message } from 'ant-design-vue';
import { useRouter } from "vue-router";
import { useCounterStore } from '@/stores/counter'
import { apiUrl } from './config'
const store = useCounterStore()
const {
    disconnect
  } = useWebSocket()
const router:any = useRouter()

const $fn = mitt()

interface axo {
    url: any,
    method?: any,
    contentType?: any,
    data?: any
}

const process = import.meta.env

const CancelToken = axios.CancelToken
NProgress.configure({ showSpinner: false })
const request = axios.create({
    // baseURL: '/v1',
    baseURL: apiUrl,
    // baseURL: 'http://192.168.1.14:8787/v1',
    timeout: Number(process.AJAX_TIMEOUT) * 1000,
    headers: {
        'Content-Type': 'application/json; charset=UTF-8',
        // 'x-requested-with': 'XMLHttpRequest'
    }
})

function getUrl(o: any) {
    const sysName = '-swordfish'
    const baseConfig: any = {};
    let pathname: any = location.pathname || '' // 当前url地址
    // let baseUrl: string = process.BASE_URL || ''
    let baseUrl: string = process.VITE_APP_BASE_URL || ''
    let base_url: any = ''
    if (pathname.indexOf(sysName) > -1) {
        pathname = pathname.split(sysName)
        baseUrl = pathname[0] + sysName
    }
    if (baseUrl.indexOf(sysName) > -1) {
        base_url = baseUrl.split(sysName);
        base_url = base_url[0] + sysName;
        baseConfig.route = baseConfig.route || [];
        baseConfig.route.forEach((item: any) => {
            if (item.matchPath == location.host + base_url && typeof item.config == 'object') {
                item.config.micro = item.config.micro || []
                item.config.micro.forEach((v: any) => {
                    if (o.url.indexOf(v.head) > -1) {
                        base_url = (v.url || item.config.url)
                    }
                })
            }
        });
    }
    return base_url + o.url
}

request.interceptors.request.use(function (config: any) {
    // 在发送请求之前做些什么
    let data = config.data || {}
    const locale = localStorage.locale
    // console.log(localStorage.getItem('token'),'token')
    config.headers['Authorization'] = localStorage.getItem('token') as never
    config.headers.type = localStorage.loginType as never
    config.headers = { ...config.headers, ...config.header }
    if (typeof data === 'string') {
        data = JSON.parse(data)
        config.data = data
    }
    // config.onUploadProgress = (event: any) => {
    //     if (event.lengthComputable) {
    //         let progress: any = (event.loaded / event.total) * 100;
    //         console.log('event', event, progress)
    //     }
    // }
    config.data = config.data || {}
    if (locale && config.data) {
        config.data.language = locale
        config.data.lang = locale
    }
    if (config.method === 'get' || config.method === 'GET') {
        let pms = ''
        Object.keys(data).forEach((v, i) => {
            if (pms === '') {
                pms = v + '=' + data[v]
            } else {
                pms += '&' + v + '=' + data[v]
            }
        })
        if (config.url.indexOf('?') === -1 && pms !== '') {
            config.url = config.url + '?' + pms
        } else if (pms !== '') {
            config.url = config.url + '&' + pms
        }
    }
    if (config.headers['Content-Type'].indexOf('application/x-www-form-urlencoded') > -1) {
        const d = new URLSearchParams()
        Object.keys(data).forEach((v, i) => {
            d.append(v, data[v])
        })
        config.data = d
    }
    if (config.loading !== false) {
        NProgress.start()
    }
    delete config.loading
    config.cancelToken = new CancelToken(function executor(c) {
        if (typeof config.cancel === 'function') {
            config.cancel(c)
        }
    })
    delete config.cancel

    if (process.MODE == 'production') {
        // config.url = process.VITE_APP_APIURL + config.url
    } else {
        config.url = getUrl({ url: config.url })
    }
    //
    return config
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
})

request.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    NProgress.done()
    const data = response.data
    if (data.code == 0) {
        localStorage.removeItem('token')
        // location.href = '/loading'
        // router.replace('/loading')
        // $fn.emit('loginAppCheck')
    }
    if(data.code == 200) {
        return data
    } else if(data.code == 401){
        message.error(data.message);
        // 判断token过期重新登陆
        store.Logout()
        disconnect() // 关闭连接
        setTimeout(() => {
            router.replace(`/login`);
        }, 2000)
        return data
    }else{
        message.error(data.message);
        return data
    }
}, function (error) {
    // 对请求错误做些什么
    NProgress.done()
    const d = error.response.data
    // if (d.code == 401) {
    //     location.href = process.BASE_URL + 'login/' + localStorage.loginType
    //     router.push({ name: 'login', params: { type: localStorage.loginType || 'admin' }})
    //     return
    // }
    if (typeof error.response === 'object') {
        // showToast(error.response.data.message)
        return Promise.reject(error.response.data)
    } else {
        return error
    }
})

export default request
